package yz.cp.back.auth.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import yz.cp.back.common.utils.Assert;

/**
 * @author xukk
 */
@Slf4j
public class SecurityUtils {

    public static Authentication getSubject() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public static SecUser getSecUser() {
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            Assert.checkArgument(false, "无法读取用户");
            return null;
        }
        Object o =authentication.getPrincipal();
        if (o instanceof SecUser) {
            SecUser secUser = (SecUser) o;
            Assert.checkNotNull(secUser.getId(), "无法读取用户");
            return secUser;
        } else {
            Assert.checkArgument(false, "无法读取用户");
            return null;
        }
    }

    public static SecUser getSecUserOrNo() {
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            return null;
        }
        Object o =authentication.getPrincipal();
        if (o instanceof SecUser) {
            SecUser secUser = (SecUser) o;
            return secUser;
        } else {
            return null;
        }
    }

    public static String getSecUserId() {
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            Assert.checkArgument(false, "无法读取用户");
            return null;
        }
        Object o =authentication.getPrincipal();
        if (o instanceof SecUser) {
            SecUser secUser = (SecUser) o;
            String id = secUser.getId();
            Assert.checkNotNull(id, "无法读取用户");
            return id;
        } else {
            Assert.checkArgument(false, "无法读取用户");
            return null;
        }

    }

    public static String getSecUserIdOrNo() {
        Authentication authentication= SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            return null;
        }
        Object o =authentication.getPrincipal();
        if (o instanceof SecUser) {
            SecUser secUser = (SecUser) o;
            String id = secUser.getId();
            return id;
        } else {
            return null;
        }

    }

}
